package wang.chunfan.code.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

/**
 * @version 1.0
 * @Author wangchunfan
 * @Date 2020/6/1 10:43
 **/
public class MultiplexerTimeServer implements Runnable {

    private Selector selector;
    private ServerSocketChannel serverSocketChannel;
    private volatile boolean stop;

    /**
     * 初始化
     */
    public MultiplexerTimeServer(int port) {
        try {
            // 创建多路复用器
            selector = Selector.open();
            // 创建 ServerSocketChannel
            serverSocketChannel = ServerSocketChannel.open();
            // 设置为非阻塞模型
            serverSocketChannel.configureBlocking(false);
            // 绑定端口,backlog  队列的最大长度
            serverSocketChannel.socket().bind(new InetSocketAddress(port), 1024);
            // 将 ServerSocketChannel 注册到 selector,并监听接受就绪
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            System.out.println("The time server is start in port:" + port);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void stop() {
        this.stop = true;
    }

    @Override
    public void run() {
        while (!stop) {
            try {
                // 轮询可用事件，每隔 1s 被唤醒
                selector.select(1000);
                // 返回就绪的 ServerSocketChannel
                Set<SelectionKey> selectedKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectedKeys.iterator();
                SelectionKey selectedKey = null;
                while (iterator.hasNext()) {
                    selectedKey = iterator.next();
                    iterator.remove();
                    try {
                        // 监听到事件
                        handleInput(selectedKey);
                    } catch (Exception e) {
                        if (selectedKey != null) {
                            selectedKey.cancel();
                            if (selectedKey.channel() != null) {
                                selectedKey.channel().close();
                            }
                        }
                    }
                }
            } catch (Throwable t) {
                t.printStackTrace();
                System.exit(1);
            }
        }
        // 主动关闭多路复用器，注册在上面的 Channel 和 Pipe 等资源将自动关闭
        if (selector != null) {
            try {
                selector.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 处理 channel
     */
    private void handleInput(SelectionKey selectedKey) throws IOException {
        // 此键有效
        if (selectedKey.isValid()) {
            // 接受就绪，属于 ServerSocketChannel
            if (selectedKey.isAcceptable()) {
                ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectedKey.channel();
                // 获取就绪的 SocketChannel
                SocketChannel socketChannel = serverSocketChannel.accept();
                socketChannel.configureBlocking(false);
                // 将新的连接注册到 selector 上
                socketChannel.register(selector, SelectionKey.OP_READ);
            }
            // 读就绪，属于 SocketChannel
            if (selectedKey.isReadable()) {
                // 读取消息
                SocketChannel socketChannel = (SocketChannel) selectedKey.channel();
                ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                int len = socketChannel.read(readBuffer);
                if (len > 0) {
                    readBuffer.flip();
                    // remaining：position 到 limit 之间的元素个数
                    byte[] bytes = new byte[readBuffer.remaining()];
                    readBuffer.get(bytes);
                    String body = new String(bytes, "UTF-8");
                    System.out.println("The time server receive order:" + body);
                    String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER";
                    // 响应
                    doWrite(socketChannel, currentTime);
                } else if (len < 0) {
                    // 关闭链路
                    selectedKey.cancel();
                    socketChannel.close();
                } else {
                    // 读到 0 字节，忽略
                }
            }
        }
    }

    /**
     * 响应
     */
    private void doWrite(SocketChannel socketChannel, String currentTime) throws IOException {
        if (currentTime != null && currentTime.trim().length() > 0) {
            byte[] bytes = currentTime.getBytes();
            ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
            writeBuffer.put(bytes);
            writeBuffer.flip();
            while (writeBuffer.hasRemaining()) {
                // 不能保证一次全部写入
                socketChannel.write(writeBuffer);
            }
        }

    }
}
